﻿using Azure;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using ServiceCore.Entity;
using ServiceCore.Entity.Core;
using ServiceCore.Entity.Model;
using ServiceCore.Service;
using ServiceCore.WebApi.jwt;

namespace ServiceCore.WebApi.Controllers
{
    [Route("Api/[controller]/[action]")]
    [AllowAnonymous]
    public class AuthController : ApiBaseController
    {
        private readonly GenerateJwt _jwtService;
        private UserInfoService userService = new UserInfoService();

        public AuthController(GenerateJwt jwtService)
        {
            this._jwtService = jwtService;
        }

        /// <summary>
        /// 登录
        /// </summary>
        /// <param name="arg"></param>
        /// <returns></returns>        
        [HttpPost]
        public BaseParam<UserInfo, UserInfo> Login(BaseParam<UserInfo, UserInfo> arg)
        {
            arg = userService.User_Login(arg);
            if (string.IsNullOrEmpty(arg.ErrorMsg) == false)
                return arg;

            int expires = 0;
            var refreshToken = JwtUserFileService.CreateRefreshToken(new JwtUserInfo(arg.Data));//刷新token，用于强制jwt过期
            arg.Data.Token = this._jwtService.GenerateEncodedTokenAsync(arg.Data.Id.ToString(), refreshToken, arg.Data, ref expires);
            arg.Data.Pwd = "";

            return arg;
        }

        /// <summary>
        /// 登出
        /// </summary>
        /// <param name="arg"></param>
        /// <returns></returns>        
        [HttpPost]
        public BaseParam<long, long> LoginOut(BaseParam<long, long> arg)
        {
            //强制登出
            JwtUserFileService.RevokeRefreshToken(arg.Id.ToString());

            return arg;
        }

        [HttpGet]
        public JsonResult Version()
        {
            return Json("202508");
        }
    }
}
